<style scope lang="scss">
  .jf_box {
    .temp_btn { 
      float: right;
    }
  }
</style>

<template>
  <div class="jf_box">
    <el-input type="textarea" rows="5" class="content" v-model="curFormatValue"
      :placeholder="placeholder" @blur="verifyJson()"></el-input>
    <el-button type="text" class="temp_btn" @click="useTemplate()">使用模版</el-button>
  </div>
</template>

<script>
export default {
  name: "jsonFormat",
  props: {
    formatValue: {
      default: "",
      type: String
    },
    templateValue: {
      default: "",
      type: String
    },
    placeholder: {
      default: "",
      type: String
    },
    relation: {
      default: "",
      type: String
    }
  },
  data() {
    return {
      curFormatValue: this.formatValue
    }
  },
  watch: {
    curFormatValue() {
      this.commitJson()
    }
  },
  mounted() {
    
  },
  methods: {
    useTemplate() {
      if (window.$util.isJsonFn(this.curFormatValue) && !window.$util.jsonIsEmpty(this.curFormatValue)) {
        this.confirm("确定要使用模板吗？").then(() => {
          this.curFormatValue = this.templateValue
        })
      } else {
        this.curFormatValue = this.templateValue
      }
    },
    commitJson() {
      let temp = {
        relation: this.relation,
        data: this.curFormatValue
      }
      this.$emit("commitData", temp)
    },
    verifyJson() {
      if (!this.curFormatValue) return false
      if (!window.$util.isJsonFn(this.curFormatValue)) {
        this.alert("不是正确的Json格式!")
        return false
      }
      let result = this.verifyResult()
      if (result && !result.isVerify) {
        this.alert("模板数据中不包含属性“" + result.faildKey + "”，如果确定数据格式无误，可忽略本次提示!")
        return false
      }
    },
    verifyResult() {
      let isVerify = true
      let faildKey = ""
      let curJson = JSON.parse(this.curFormatValue)
      let tempJson = JSON.parse(this.templateValue)
      for (let i in curJson) {
        let tempHasKey = Object.prototype.hasOwnProperty.call(tempJson, i);
        if (!tempHasKey) {
          isVerify = false
          faildKey = i
          return { isVerify: isVerify, faildKey: faildKey }
        }
      }
      return null
    }
  }
}
</script>